package com.araaya.eslimsmobile.util;

import java.io.File;
import java.util.ArrayList;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.MimeTypeMap;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import com.araaya.eslimsmobile.R;

public class FileBrowserAdapter extends ArrayAdapter<File>{
	
	  private final Context context;
	  private final ArrayList<File> files;
	  private final BitmapFactory.Options options; 
	  private final LayoutInflater inflater;
	  private Bitmap imgIcon ;
	  private View rowView;
	  private TextView textView;
	  private ImageView imageView;
	  
	  /**
	   * Public constructor 
	   * @param context 
	   * @param values list if files in a directory
	   */
	  
	  public FileBrowserAdapter(Context context, ArrayList<File> values) {
		    super(context, R.layout.rowlayout, values);
		    this.options= new BitmapFactory.Options();
		    this.inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		    this.context = context;
		    this.files = values;
		  }
	  
	  @Override
	  public View getView(int position, View convertView, ViewGroup parent) {
	    rowView = inflater.inflate(R.layout.rowlayout, parent, false);
	    textView = (TextView) rowView.findViewById(R.id.fpath);
	    imageView = (ImageView) rowView.findViewById(R.id.ficon);
	    	
	    	File f = files.get(position);
			if (f.isDirectory()){
				textView.setText(f.getName()+"/");
				imageView.setImageResource(R.drawable.ic_folder);
			}else{
				Log.d("DEBUG","File: "+f.getName()+" Type: "+isImage(f));
				textView.setText(f.getName());
				if(isImage(f)){
					imgIcon= BitmapFactory.decodeFile(f.getPath(), options);
					if(imgIcon!=null){
						imageView.setImageBitmap(imgIcon);
					}else{
						imageView.setImageResource(R.drawable.ic_file);
					}
				}else{
					imageView.setImageResource(R.drawable.ic_file);
				}
				}
	    return rowView;
	  }
	  
	  /**
	   * Check whether the file has a image content
	   * @param f file
	   * @return true if the file is a image type (some times will not detect)
	   */
	  private boolean isImage(File f) {
		  String type = null;
	      String extension = MimeTypeMap.getFileExtensionFromUrl(f.getPath());
	      if (extension != null) {
	          MimeTypeMap mime = MimeTypeMap.getSingleton();
	          type = mime.getMimeTypeFromExtension(extension);
	      }
	     return type!=null && type.startsWith("image");
	}


}
